package com.ias.agdis_r.activity.flight;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;

import com.android.volley.NoConnectionError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.ias.agdis_r.R;
import com.ias.agdis_r.activity.BaseKeyActivity;
import com.ias.agdis_r.adapter.SearchDetailActivityListViewAdapter;
import com.ias.agdis_r.bean.fight.FlightQueryResult;
import com.ias.agdis_r.bean.fight.FlightQueryValue;
import com.ias.agdis_r.manager.DataManager;
import com.ias.agdis_r.manager.EffectManager;
import com.ias.agdis_r.module.MessageModel;
import com.ias.agdis_r.module.RestfulUri;
import com.ias.agdis_r.terminalmanager.restful.base.endpoint.response.BaseResponseHeader;
import com.ias.agdis_r.terminalmanager.restful.flight.endpoint.request.FlightRequest;
import com.ias.agdis_r.terminalmanager.restful.flight.endpoint.response.FlightQueryResponse;
import com.ias.agdis_r.util.S;
import com.ias.agdis_r.volley.GsonRequest;
import com.ias.agdis_r.volley.callback.BaseOnVolleyErrorAdapter;
import com.ias.agdis_r.volley.callback.BaseOnVolleyErrorListener;
import com.ias.agdis_r.volley.callback.BaseOnVolleySuccessListener;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import me.maxwin.view.XListView;

public class SearchDetailActivity extends BaseKeyActivity implements XListView.IXListViewListener {

	public static final String EXTRA_SEARCH_REQUEST_BODY_JSON_STR = SearchDetailActivity.class.getName()
			+ "_extra_req_body";

	public static final int DEFAUTL_PAGE_SIZE = 6;

	private XListView mListView;
	private SearchDetailActivityListViewAdapter mAdapter = null;
	private Handler handler;
	private ActionBar actionBar = null;

	private List<FlightQueryValue> data = new LinkedList<FlightQueryValue>();
	private RequestQueue requestQueue;
	private FlightRequest flightRequest;

	/** 查询结果的长度 */
	private int resultLength = -1;
	private boolean isRefresh = false;

	/** 请求服务器数据成功的回调 */
	private BaseOnVolleySuccessListener<FlightQueryResponse> successCallback = new BaseOnVolleySuccessListener<FlightQueryResponse>() {

		@Override
		public void onRequestSuccess(FlightQueryResponse response) {

			// 返回结果，但结果内容为空（极端情况：第一次查出，刷新无数据也直接退出）
			if (response.getFlightResponseVO() == null) {
				finishDelayedAfterToast(getString(R.string.noResult_1), 2000);
				return;
			}

			// 正常返回数据时的处理
			int num = Integer.parseInt(response.getFlightResponseVO().getNum());
			FlightQueryResult result = response.getFlightResponseVO().getResult();

			if (num > 0 && result.getFlightQueryValues().size() > 0) {
				resultLength = num;
				// 是刷新时清空数据集重新填充
				if (isRefresh) {
					data.clear();
				}
				synchronized (data) {
					data.addAll(result.getFlightQueryValues());
				}
				mAdapter.notifyDataSetChanged();
			}

			onDataLoaded();

		}

		@Override
		public void onRequestFailed(BaseResponseHeader header) {
			// TODO 状态码为0的时候，服务器发现异常未返回数据
			if (data.size() > 0) {
				toast(getString(R.string.serviceError));
				return;
			}
			finishDelayedAfterToast(header.getErrorMessage(), 1000);
			onDataLoaded();
		}
	};

	// 发送请求异常时的回调
	private BaseOnVolleyErrorListener onErrCalback = new BaseOnVolleyErrorAdapter() {

		@Override
		public void onErrorOccurred(VolleyError e) {
			
			String msg = "";
			if (e instanceof TimeoutError) {
				
				msg = getString(R.string.request_err_timeout);
			} else if (e instanceof ServerError) {
				//显示接收消息异常
				msg = getString(R.string.request_err_servererror);
			} else if (e instanceof NoConnectionError) {
				msg = getString(R.string.request_err_noconnection);
			}		
			
			if (isRefresh) {
				toast(msg);
			}
			else
			{
				finishDelayedAfterToast(msg, 1000);
			}
			onDataLoaded();
		};

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_searchdetail);

		actionBar = getActionBar();
		initActionBarSearchInfo();
		this.handler = new Handler();

		mListView = (XListView) findViewById(R.id.xListView);
		mListView.setPullLoadEnable(false);
		mAdapter = new SearchDetailActivityListViewAdapter(SearchDetailActivity.this, data);
		mListView.setAdapter(mAdapter);

		String req = getIntent().getExtras().getString(EXTRA_SEARCH_REQUEST_BODY_JSON_STR);
		requestQueue = Volley.newRequestQueue(this);
		try {
			flightRequest = DataManager.getInstance().getMapper().readValue(req, FlightRequest.class);
		} catch (IOException e) {
			e.printStackTrace();
		}

		loadData();
		mListView.setRefreshTime(getFormatedTimeForHearder());
		mListView.startRefreshView();

		mListView.setXListViewListener(SearchDetailActivity.this);

		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Log.i("C_index", position + "VS" + id);
				if (id < 0) {
					return;
				}
				Intent intent = new Intent(SearchDetailActivity.this, SearchInfoActivity.class);
				intent.putExtra(SearchInfoActivity.EXTRA_FLIGHT_SEQ, data.get((int) id).getFKE());
				startActivity(intent);
			}
		});
	}

	/**
	 * Toast一个消息，一段时间后退出当前Activity
	 * 
	 * @param msg 弹出消息内容
	 * @param delayedMillis 延迟时间
	 */
	private void finishDelayedAfterToast(String msg, long delayedMillis) {
		if (S.isNotEmpty(msg)) {
			toast(msg);
		}
		if (delayedMillis >= 0) {
			handler.postDelayed(new Runnable() {

				@Override
				public void run() {
					finish();
				}
			}, delayedMillis);
		}
	}

	// 弹出提示信息以提醒用户
	private void toast(String msg) {
		EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, msg, false);
	}

	/**
	 * 加载数据
	 */
	private void loadData() {
		Request<FlightQueryResponse> request = null;
		try {
			request = new GsonRequest<FlightQueryResponse>(
                    RestfulUri.getUri(MessageModel.QFIQ), FlightQueryResponse.class, DataManager.getInstance().getMapper().writeValueAsString(flightRequest),
                    this.successCallback, this.onErrCalback);
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}
		requestQueue.add(request);
	}

	/**
	 * 获取格式化的当前时间
	 * 
	 * @return时间格式“HH:mm:ss”
	 */
	@SuppressLint("SimpleDateFormat")
	private String getFormatedTimeForHearder() {
		SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
		Date curDate = new Date(System.currentTimeMillis());
		return formatter.format(curDate);
	}

	/**
	 * 数据加载完成的后续处理
	 */
	private void onDataLoaded() {
		String str = getFormatedTimeForHearder();

		if (resultLength == 0) {
			// TODO 查不到数据
		} else if (data.size() < resultLength) {
			// TODO 还有更多数据
			mListView.setPullLoadEnable(true);
		} else {
			// TODO 没有更多数据了
			mListView.setPullLoadEnable(false);
		}

		mListView.stopRefresh();
		mListView.stopLoadMore();
		mListView.setRefreshTime(str);
	}

	@Override
	public void onRefresh() {
		isRefresh = true;
		flightRequest.getFlightVO().setNum(data.size() + "");
		flightRequest.getFlightVO().setIdx("0");
		loadData();
	}

	@Override
	public void onLoadMore() {
		isRefresh = false;
		if (resultLength > data.size()) {
			int page = data.size() / DEFAUTL_PAGE_SIZE;
			flightRequest.getFlightVO().setIdx(page + "");
			flightRequest.getFlightVO().setNum(DEFAUTL_PAGE_SIZE + "");
			loadData();
		}
	}

	private void initActionBarSearchInfo() {
		// TODO Auto-generated method stub
		actionBar.setCustomView(
				LayoutInflater.from(SearchDetailActivity.this).inflate(R.layout.actionbar_searchdetail, null));
		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
		actionBar.setDisplayShowCustomEnabled(true);
		ImageView back = (ImageView) findViewById(R.id.actionbar_seletcdetail_back);
		back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				finish();
			}
		});
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(null != requestQueue)
		requestQueue.stop();
	}
}
